package com.wmada.toolkit.rest.builder;

import com.wmada.toolkit.rest.DownloadException;
import org.apache.http.client.utils.URIBuilder;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author will.ma
 * @date 2019-4-25
 */
@SuppressWarnings("unused")
public class ParamBuilder {

    private final Map<String, String[]> params = new LinkedHashMap<>();

    private ParamBuilder() {
    }

    public static ParamBuilder create() {
        return new ParamBuilder();
    }

    public ParamBuilder add(String key) {
        return add(key, null);
    }

    public ParamBuilder add(String key, String value) {
        params.compute(key, (k, v) -> {
            String[] list = v == null ? new String[1] : Arrays.copyOf(v, v.length + 1);
            list[list.length - 1] = value;
            return list;
        });
        return this;
    }

    public Map<String, String[]> build() {
        return params;
    }

    public static URI buildUrl(String url, Map<String, String[]> params) throws DownloadException {
        try {
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
                for (Map.Entry<String, String[]> entry : params.entrySet()) {
                    for (String val : entry.getValue()) {
                        builder.addParameter(entry.getKey(), val);
                    }
                }
            }
            return builder.build();
        } catch (URISyntaxException e) {
            throw new DownloadException(e, null, DownloadException.STATUS_WRONG_URL_FORMAT);
        }
    }

}
